package com.miku.blog.filter;

import com.miku.blog.domain.pojo.LoginUser;
import com.miku.blog.domain.pojo.SystemConstance;
import com.miku.blog.eume.HttpStatusEnum;
import com.miku.blog.utils.JwtUtils;
import com.miku.blog.utils.RedisCache;
import com.miku.blog.utils.WebUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


/**
 * @author shkstart
 * @create ${}YEAR-05-24 23:54
 */

@Deprecated
public class JwtAuthenticationFilter extends OncePerRequestFilter {


    private RedisCache redisCache;

    public JwtAuthenticationFilter(){

    }

    public JwtAuthenticationFilter(RedisCache redisCache){
        this.redisCache = redisCache;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        StringBuffer requestURL = request.getRequestURL();
        String token = (String) request.getAttribute("token");
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        Claims claims = null;
        try {
            claims = JwtUtils.parseJwt(token);
        } catch (ExpiredJwtException exception) {
            exception.printStackTrace();
            WebUtils.sendResponseResult(response,HttpStatusEnum.NEED_LOGIN_AGAIN);
            return;
        } catch (MalformedJwtException m){
            m.printStackTrace();
            WebUtils.sendResponseResult(response,HttpStatusEnum.TOKEN_UNLAWFUL);
            return;
        }
        String userId = claims.getSubject();
        LoginUser loginUser = redisCache.getCacheObject(SystemConstance.REDIS_LOGINUSER_KEY + userId);
        if (Objects.isNull(loginUser)){
            WebUtils.sendResponseResult(response,HttpStatusEnum.NEED_LOGIN_AGAIN);
            return;
        }
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }

}

